package corej.prj.chatRoom.Dan;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class ChatClient {
    private JTextArea jta;

    private JTextField jtf;

    private Socket socket;

    private BufferedReader in;

    private PrintWriter out;

    public ChatClient() {
        JFrame frame = new JFrame("family Dan");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jta = new JTextArea();
        jtf = new JTextField();
        frame.add(new JScrollPane(jta));
        frame.add(jtf, "South");

        jta.setEditable(false);

        frame.setVisible(true);

        jtf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String text = jtf.getText();
                out.println(text + '\n');
                jtf.setText("");
            }
        });

        try {
            socket = new Socket("127.0.0.1", 9000);
            in = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
            OutputStream os = socket.getOutputStream();
            out = new PrintWriter(os, true);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void receive() {
        try {
            while (true) {
                String message = in.readLine();
                jta.append(message + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ChatClient c = new ChatClient();
        c.receive();
    }

}
